#coding=utf-8
#LightCam 批量执行程序
#init by hfh 20150827

import multiprocessing,subprocess,threading
import socket,os,time,re,traceback,sys
import lc_libs

def func_cmd(this):
	
	hostname=this['hostname']
	ip=this['ip']
	area=this['area']
	ostype=this['ostype'].lower()

	try:
		comd=""
		if ostype in ("linux","aix","hpux"):
			if area=='monitor':
				comd='''ssh %s ". ~/.bash_profile;%s" ''' % (hostname,Comand)
			elif area=='yww':
				comd='''ssh yww_monitor1 "ssh %s ". ~/.bash_profile\\\\\\;%s""''' % (hostname,Comand)
				if ostype in ('aix','hpux'):
					comd='''ssh yww_monitor1 "ssh %s ". ~/.profile\\\\\\;%s""''' % (hostname,Comand)
			elif area=='ywn':
				comd='''ssh ywn_monitor1 "ssh config3 "ssh %s ". \\\\\\\\\\\\~/.bash_profile\\\\\\\\\\\\;%s"""''' % (hostname,Comand)
				if ostype in ('aix','hpux'):
					comd='''ssh ywn_monitor1 "ssh config3 "ssh %s ". ~/.profile\\\\\\\\\\\\;%s"""''' % (hostname,Comand)
		else:
			if area=='monitor':
				comd='''ssh %s "%s" ''' % (hostname,Comand)
			elif area=='yww':
				comd='''ssh yww_monitor1 "ssh %s "%s""''' % (hostname,Comand)
			elif area=='ywn':
				comd='''ssh ywn_monitor1 "ssh config3 "ssh %s "%s"""''' % (hostname,Comand)
		#print comd
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		#判断子进程是否结束
		#while True:
		#	if popen.poll()==None:
		#		time.sleep(0.1)
		#		continue
		#	else:
		#		break
		print "#################### Command Result on %s ####################" % hostname
		print popen.stdout.read()
		print "#################### End of Result on %s  ####################" % hostname
	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		time.sleep(1)

def func_put(this):
	
	hostname=this['hostname']
	ip=this['ip']
	area=this['area']
	ostype=this['ostype']

	try:
		comd=""
		if area=='monitor':
			comd='''scp -p %s %s:%s/%s''' % (LocalFile,hostname,RemotePath,RemoteFile)
			os.system(comd)
		elif area=='yww':
			comd='''scp -p %s yww_monitor1:/monitor/LightCam/temp/%s''' % (LocalFile,RemoteFile)
			os.system(comd)
			comd='''ssh yww_monitor1 "scp -p /monitor/LightCam/temp/%s %s:%s/%s"''' % (RemoteFile,hostname,RemotePath,RemoteFile)
			os.system(comd)
		elif area=='ywn':
			comd='''scp -p %s ywn_monitor1:/monitor/LightCam/temp/%s''' % (LocalFile,RemoteFile)
			os.system(comd)
			comd='''ssh ywn_monitor1 "scp -p /monitor/LightCam/temp/%s config3:/monitor/LightCam/temp/%s"''' % (RemoteFile,RemoteFile)
			os.system(comd)
			comd='''ssh ywn_monitor1 "ssh config3 "scp -p /monitor/LightCam/temp/%s %s:%s/%s""''' % (RemoteFile,hostname,RemotePath,RemoteFile)
			os.system(comd)

	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		time.sleep(1)
		

def func_get(this):
	
	hostname=this['hostname']
	ip=this['ip']
	area=this['area']
	ostype=this['ostype']
	
	try:
		comd=""
		if area=='monitor':
			comd='''scp -p %s:%s %s/%s''' % (hostname,RemoteFile,LocalPath,LocalFile)
			os.system(comd)
		elif area=='yww':
			comd='''ssh yww_monitor1 "scp -p %s:%s /monitor/LightCam/temp/%s"''' % (hostname,RemoteFile,LocalFile)
			os.system(comd)
			comd='''scp -p yww_monitor1:/monitor/LightCam/temp/%s %s/%s''' % (LocalFile,LocalPath,LocalFile)
			os.system(comd)
		elif area=='ywn':
			comd='''ssh ywn_monitor1 "ssh config3 "scp -p %s:%s /monitor/LightCam/temp/%s""''' % (hostname,RemoteFile,LocalFile)
			os.system(comd)
			comd='''ssh ywn_monitor1 "scp -p config3:/monitor/LightCam/temp/%s /monitor/LightCam/temp/%s"''' % (LocalFile,LocalFile)
			os.system(comd)
			comd='''scp -p ywn_monitor1:/monitor/LightCam/temp/%s %s/%s''' % (LocalFile,LocalPath,LocalFile)
			os.system(comd)

	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		time.sleep(1)
		

def func_getsp(this):
	
	hostname=this['hostname']
	ip=this['ip']
	area=this['area']
	ostype=this['ostype']
	
	try:
		comd=""
		if area=='monitor':
			comd='''scp -p %s:%s %s/%s_%s''' % (hostname,RemoteFile,LocalPath,hostname,LocalFile)
			os.system(comd)
		elif area=='yww':
			comd='''ssh yww_monitor1 "scp -p %s:%s /monitor/LightCam/temp/%s_%s"''' % (hostname,RemoteFile,hostname,LocalFile)
			os.system(comd)
			comd='''scp -p yww_monitor1:/monitor/LightCam/temp/%s_%s %s/%s_%s''' % (hostname,LocalFile,LocalPath,hostname,LocalFile)
			os.system(comd)
		elif area=='ywn':
			comd='''ssh ywn_monitor1 "ssh config3 "scp -p %s:%s /monitor/LightCam/temp/%s_%s""''' % (hostname,RemoteFile,hostname,LocalFile)
			os.system(comd)
			comd='''ssh ywn_monitor1 "scp -p config3:/monitor/LightCam/temp/%s_%s /monitor/LightCam/temp/%s_%s"''' % (hostname,LocalFile,hostname,LocalFile)
			os.system(comd)
			comd='''scp -p ywn_monitor1:/monitor/LightCam/temp/%s_%s %s/%s_%s''' % (hostname,LocalFile,LocalPath,hostname,LocalFile)
			os.system(comd)

	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		time.sleep(1)
		



if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	logfile=file(logfilename,'a')
	#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	#logfile.write(logdate+" Started.\n")
	#logfile.flush()
	
	agent_hostname=lc_libs.lc_gethostname()

	#初始化
	length = len(sys.argv)
	
	strs='''
	Wrong para, please input hostlist operation argv :
	1. hostlist:
		all means all 
		ywn|yww|monitor means by area
		linux|aix|hpux|windows means by os
		front1|mondb2 means one server
	2. operation:
		2.1 comand:
			LightCamPy lc_batch.py aix cmd 'Comand'
		2.2 putfile:
			LightCamPy lc_batch.py ywn put LocalFile RemoteFile RemotePath
		2.3 getfile:
			LightCamPy lc_batch.py ywn get RemoteFile LocalFile LocalPath
		2.3 getfile_sp:
			LightCamPy lc_batch.py ywn getsp RemoteFile LocalFile LocalPath
	'''
		
	if length<4:
		print strs
		exit(0)
	
	hostlist=sys.argv[1]
	operation=sys.argv[2]
	
	Comand=""
	LocalFile=""
	RemoteFile=""
	RemotePath=""
	LocalPath=""
	
	if operation not in ("cmd","put","get","getsp"):
		print strs
		exit(0)
	elif operation == 'cmd':
		Comand=sys.argv[3]
	elif operation == 'put':
		LocalFile=sys.argv[3]
		RemoteFile=sys.argv[4]
		RemotePath=sys.argv[5].rstrip("/")
	elif operation in ('get','getsp'):
		RemoteFile=sys.argv[3]
		LocalFile=sys.argv[4]
		LocalPath=sys.argv[5].rstrip("/")

	#主程序
	MonitorList = []
	confname=lchome+'/conf/lc_hostlist.conf'

	if hostlist=="all":
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				if line[0] == 'mondb1':
					continue
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				MonitorList.append(dconf)
	elif hostlist=="ywn":
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				if line[0] == 'mondb1':
					continue
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				if dconf['area'] != 'ywn':
					continue
				MonitorList.append(dconf)
	elif hostlist=="yww":
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				if line[0] == 'mondb1':
					continue
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				if dconf['area'] != 'yww':
					continue
				MonitorList.append(dconf)
	elif hostlist=="monitor":
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				if line[0] == 'mondb1':
					continue
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				if dconf['area'] != 'monitor':
					continue
				MonitorList.append(dconf)
	elif hostlist=="linux":
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				if line[0] == 'mondb1':
					continue
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				if dconf['ostype'].lower() != 'linux':
					continue
				MonitorList.append(dconf)
	elif hostlist=="aix":
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				if line[0] == 'mondb1':
					continue
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				if dconf['ostype'].lower() != 'aix':
					continue
				MonitorList.append(dconf)
	elif hostlist=='windows':
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				if line[0] == 'mondb1':
					continue
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				if "windows" not in dconf['ostype'].lower():
					continue
				MonitorList.append(dconf)
	elif hostlist=='hpux':
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				if line[0] == 'mondb1':
					continue
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				if dconf['ostype'].lower() != 'hpux':
					continue
				MonitorList.append(dconf)
	else:
			for lines in open(confname):
				if lines[0] == '#':
					continue
				line=lines.strip('\r\n').split('\t')
				dconf={}
				dconf['hostname']=line[0]
				dconf['ip']=line[1]
				dconf['area']=line[2]
				dconf['ostype']=line[3]
				if dconf['hostname'] not in hostlist.split('|'):
					continue
				MonitorList.append(dconf)

	
	threads = []
	if operation=="cmd":
		for i in MonitorList:
			t = threading.Thread(target=func_cmd,args=(i,))
			threads.append(t)
		for t in threads:
			t.start()
			while True:
				#print len(threading.enumerate())
				time.sleep(0.01)
				if(len(threading.enumerate()) < 10):
					break
	elif operation=="put":
		for i in MonitorList:
			t = threading.Thread(target=func_put,args=(i,))
			threads.append(t)
		for t in threads:
			t.start()
			while True:
				#print len(threading.enumerate())
				time.sleep(0.01)
				if(len(threading.enumerate()) < 10):
					break
		while len(threading.enumerate())>1:
			time.sleep(1)
		comd='''ssh yww_monitor1 "rm -f /monitor/LightCam/temp/%s"''' % (RemoteFile)
		os.system(comd)
		comd='''ssh ywn_monitor1 "rm -f /monitor/LightCam/temp/%s"''' % (RemoteFile)
		os.system(comd)
		comd='''ssh ywn_monitor1 "ssh config3 "rm -f /monitor/LightCam/temp/%s""''' % (RemoteFile)
		os.system(comd)
	elif operation=="get":
		for i in MonitorList:
			t = threading.Thread(target=func_get,args=(i,))
			threads.append(t)
		for t in threads:
			t.start()
			while True:
				#print len(threading.enumerate())
				time.sleep(0.01)
				if(len(threading.enumerate()) < 10):
					break
		while len(threading.enumerate())>1:
			time.sleep(1)
		comd='''ssh yww_monitor1 "rm -f /monitor/LightCam/temp/%s"''' % (LocalFile)
		os.system(comd)
		comd='''ssh ywn_monitor1 "rm -f /monitor/LightCam/temp/%s"''' % (LocalFile)
		os.system(comd)
		comd='''ssh ywn_monitor1 "ssh config3 "rm -f /monitor/LightCam/temp/%s""''' % (LocalFile)
		os.system(comd)
	elif operation=="getsp":
		for i in MonitorList:
			t = threading.Thread(target=func_getsp,args=(i,))
			threads.append(t)
		for t in threads:
			t.start()
			while True:
				#print len(threading.enumerate())
				time.sleep(0.01)
				if(len(threading.enumerate()) < 10):
					break
		while len(threading.enumerate())>1:
			time.sleep(1)
		comd='''ssh yww_monitor1 "rm -f /monitor/LightCam/temp/%s_%s"''' % (i['hostname'],LocalFile)
		os.system(comd)
		comd='''ssh ywn_monitor1 "rm -f /monitor/LightCam/temp/%s_%s"''' % (i['hostname'],LocalFile)
		os.system(comd)
		comd='''ssh ywn_monitor1 "ssh config3 "rm -f /monitor/LightCam/temp/%s_%s""''' % (i['hostname'],LocalFile)
		os.system(comd)

